package com.yonghui;


import java.util.*;
import java.util.concurrent.TimeUnit;

public class WeakHashMapTest {

    public static void main(String[] args) {
        myHashMap();
        myWeakHashMap();
    }

    public static void myHashMap(){
        String key=new String("key");
        HashMap map=new HashMap();
        map.put(key,new Object());
        iter("HashMap",map);
        key=null;
        System.gc();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        iter("HashMap",map);
    }


    public static void myWeakHashMap(){
        String key=new String("key");
        WeakHashMap map=new WeakHashMap();
        map.put(key,new Object());
        iter("MyhashMap",map);
        key=null;
        System.gc();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        iter("MyhashMap",map);
    }

    public static  void iter(String desc,Map map){
        map.forEach((k, v) -> {
            System.out.println(desc+"======key："+k+"，value："+v);
        });
        System.out.println(desc+".size()："+map.size());
    }
}
